define([ './module' ], function(promotiontopicmodule) {
	'use strict';

	promotiontopicmodule.controller('promotiontopic',['$scope','$http','$location','Upload','$timeout',function($scope,$http,$location,Upload,$timeout){

		//图片上传files
		$scope.$watch('files',function(){
			$scope.upload($scope.files);
		});
		$scope.allupimgs=[];
		$scope.upload=function(files){
			if(files&&files.length){
				for(var i=0;i<files.length;i++){
					var file=files[i];
					var filename=files[i].name;
					if(!file.$error){
						Upload.upload({
							url:'../mall/files/ajaxFileUploadsImgs.action',
							data:{
								file:file,
								'filename':filename
							}
						}).progress(function (evt) {
		                    var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
		                    $scope.progress=progressPercentage;
		                }).success(function (data, status, headers, config) {
		                    $timeout(function() {
		                    	if(data.sucflag){
		                    		$scope.allupimgs.push(data);
		                    	}
		                    });
		                    
		                });
					}
				}
			}
		}
		
		$scope.remove=function(index){
			$scope.allupimgs.splice(index,1);
		}
		
		//通过location中的operate参数区分操作行为
		var operate=$location.search().operate;
		if(operate!=undefined&&operate=="save"){
			//控制保存按钮显示
			$scope.savebtn={show:true};
			$scope.title='添加专题促销';
			$scope.status="1";
			$scope.isvisible="1";
			$scope.iscommendtoindex="1";
			$scope.ismaincommend="0";
			$scope.save=function(){

				if($scope.topictitle==undefined){
					$scope.errors={
							show:true,
							msg:'请输入专题标题'
					}
					return false;
				}
				if($scope.des==undefined){
					$scope.errors={
							show:true,
							msg:'请输入简介'
					}
					return false;
				}
				if($scope.vol==undefined){
					$scope.errors={
							show:true,
							msg:'请输入期号'
					}
					return false;
				}
				$http({
					method:'POST',
					url:'../mall/promotion/topic/save.action',
					data:{
						"des":$scope.des,
						"isvisible":$scope.isvisible,
						"mainimg":angular.toJson($scope.allupimgs),
						"topictitle":$scope.topictitle,
						"vol":$scope.vol,
						"status":$scope.status,
						"iscommendtoindex":$scope.iscommendtoindex,
						"ismaincommend":$scope.ismaincommend
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'添加专题成功'
						}
						$location.path('/promotiontopicment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});

			}
		}

		if(operate=='edit'){
			var id=$location.search().id;
			if(id!=undefined&&id!=""){
				$http({
					method:'POST',
					url:'../mall/promotion/topic/find.action',
					data:{
						'id':id
					}
				}).success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.title='正在对专题--'+data.bean.topictitle+'--进行编辑';
						$scope.des=data.bean.des;
						$scope.iscommendtoindex=data.bean.iscommendtoindex;
						$scope.ismaincommend=data.bean.ismaincommend;
						$scope.isvisible=data.bean.isvisible;
						$scope.vol=data.bean.vol;
						$scope.topictitle=data.bean.topictitle;
						$scope.allupimgs.push(data.ifb);
						$scope.iscommendtoindex=data.bean.iscommendtoindex;
						$scope.ismaincommend=data.bean.ismaincommend;
						$scope.status=data.bean.status;
						$scope.updatebtn={show:true};
					}
				}).error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}

			//更新货物
			$scope.update=function(){
				if($scope.topictitle==undefined){
					$scope.errors={
							show:true,
							msg:'请输入专题标题'
					}
					return false;
				}
				if($scope.des==undefined){
					$scope.errors={
							show:true,
							msg:'请输入简介'
					}
					return false;
				}
				if($scope.vol==undefined){
					$scope.errors={
							show:true,
							msg:'请输入期号'
					}
					return false;
				}

				$http({
					method:'POST',
					url:'../mall/promotion/topic/update.action',
					data:{
						"des":$scope.des,
						"isvisible":$scope.isvisible,
						"mainimg":angular.toJson($scope.allupimgs),
						"topictitle":$scope.topictitle,
						"vol":$scope.vol,
						"status":$scope.status,
						"iscommendtoindex":$scope.iscommendtoindex,
						"ismaincommend":$scope.ismaincommend,
						"id":id
					}
				})
				.success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'专题更新成功'
						}
						$location.path('/promotiontopicment');
					}
				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}

		}
	}]);

	promotiontopicmodule.controller('promotiontopicment',ServerpromotiontopicmentCtrl);
	//查询列表数据
	function ServerpromotiontopicmentCtrl($http,$location,$compile,$scope,$rootScope,$resource,DTOptionsBuilder,DTColumnBuilder,DTAjaxRenderer){
		var vm=this;
		vm.message='';
		vm.someClickHandler = someClickHandler;
		vm.selected={};
		vm.selectAll=false;
		vm.toggleAll=toggleAll;
		vm.toggleOne=toggleOne;
		vm.dtInstance={};
		var titleHtml='<input type="checkbox" ng-model="showCase.selectAll" ng-click="showCase.toggleAll(showCase.selectAll,showCase.selected)">';
		vm.dtOptions=DTOptionsBuilder.newOptions().withOption('ajax',{
			type:'POST',
			url:'../mall/promotion/topic/findByPage.action',
			dataSrc:'data'
		})
		.withOption('processing',true)
		.withOption('paging',true)
		.withOption('serverSide',true)
		.withOption('createdRow',function(row,data,dataIndex){
			$compile(angular.element(row).contents())($scope);
		})
		.withOption('headerCallback', function(header) {
            if (!$scope.headerCompiled) {
                $scope.headerCompiled = true;
                $compile(angular.element(header).contents())($scope);
            }
        })
        .withOption('stateSave', true)
        .withOption('rowCallback',rowCallback)
		.withPaginationType('full_numbers')
		.withLanguageSource('./app/language/chinese.json')

		$scope.$on('handleRequest',function(){

		});
		vm.dtColumns=[
		              DTColumnBuilder.newColumn(null).withTitle(titleHtml).notSortable().renderWith(function(data,type,full,meta){
		            	  vm.selected[full.id]=false;
		            	  return "<input type='checkbox' ng-model=\"showCase.selected['"+data.id+"']\" ng-click=\"showCase.toggleOne(showCase.selected)\">";
		              }),
		              DTColumnBuilder.newColumn('id').withTitle('ID').notVisible(),
		              DTColumnBuilder.newColumn(null).withTitle('图片').notSortable().renderWith(imgHtml),
			          DTColumnBuilder.newColumn('topictitle').withTitle('专题标题').notSortable(),
			          DTColumnBuilder.newColumn('vol').withTitle('专题号').notSortable(),
			          DTColumnBuilder.newColumn('iscommendtoindex').withTitle('推荐首页状态').notSortable(),
			          DTColumnBuilder.newColumn('ismaincommend').withTitle('主推荐状态').notSortable(),
			          DTColumnBuilder.newColumn('isvisible').withTitle('显示状态').notSortable(),
			          DTColumnBuilder.newColumn('status').withTitle('状态').notSortable(),
			          DTColumnBuilder.newColumn('updatetime').withTitle('更新时间').notSortable(),
			          DTColumnBuilder.newColumn('version').withTitle('版本号').notSortable(),
			          DTColumnBuilder.newColumn(null).withTitle('操作').notSortable().renderWith(actionHtml)];
		function imgHtml(data,type,full,meta){
			return '<img style="width:50px;height:50px;" ng-src="'+data.mainimg+'" alt="Photo" />';
		}
		function actionHtml(data,type,full,meta){
			return "<button  ng-click=\"edit('"+data.id+"')\" class='btn btn-warning'><i class='fa fa-edit'></i></button>" +
					"&nbsp;&nbsp;<button  ng-click=\"findAllContent('"+data.id+"')\" class='btn btn-success'><i class='fa fa-camera-retro'></i></button>";
		}

		function reloadData(){
			var resetPaging = false;
	        vm.dtInstance.reloadData(callback, resetPaging);
		}
		function callback(data){
		}


		//表格中编辑按钮
		$scope.edit=function(id,name){
			$location.path('/promotiontopic').search({'operate':'edit','id':id});
		}
		
		/**
		 * 查询所有专题内容
		 */
		$scope.findAllContent=function(id,name){
			$location.path('/promotiontopiccontentment').search({'operate':'save','id':id});
		}

		/**
		 * 跳转到添加商品类型和参数页面
		 */
		$scope.save=function(){
			$location.path('/promotiontopic').search({'operate':'save'});
		}

		$scope.del=function(){
			var i=0;
			var ids=[];
			angular.forEach(vm.selected, function(data,index,array){
				if(data){
					i++;
					ids.push(index);
				}
			});
			if(i==0){
				$scope.errors={
						show:true,
						msg:'请选择一条记录'
				}
			}else{
				$scope.errors={
						show:false
				}
				//批量删除数据
				var idstrs=ids.join(",");
				$http({
					method:'POST',
					url:'../mall/promotion/topic/del.action',
					data:{
						'ids':idstrs
					}
				}).
				success(function(data,status,headers,config){
					if(data.sucflag){
						$scope.errors={};
						$scope.info={
								show:true,
								msg:'删除成功'
						}
						reloadData();
					}

				}).
				error(function(data,status,headers,config){
					$scope.errors={
							show:true,
							msg:'系统异常'
					}
				});
			}
		}

		/**
		 * 列表全选
		 */
		function toggleAll(selectAll,selectedItems){
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					selectedItems[id]=selectAll;
				}
			}
		}
		/**
		 * 列表单选
		 */
		function toggleOne(selectedItems){
			var me=this;
			for(var id in selectedItems){
				if(selectedItems.hasOwnProperty(id)){
					if(!selectedItems[id]){
						me.selectAll=false;
					}
				}
			}
			me.selectAll=true;
		}

		function someClickHandler(info) {
	        vm.message = info.id + ' - ' + info.name;
	    }
		/**
		 * 单击列表某行回调
		 */
		function rowCallback(nRow,aData,iDisplayIndex,iDisplayIndexFull){
			$('td', nRow).unbind('click');
	        $('td', nRow).bind('click', function() {
	            $scope.$apply(function() {
	                vm.someClickHandler(aData);
	            });
	        });
	        return nRow;
		}

	}
});
